package com.grass.finding.controller;

import com.grass.finding.common.BaseResponse;
import com.grass.finding.common.ErrorCode;
import com.grass.finding.exception.BusinessException;
import com.grass.finding.model.domain.Comments;
import com.grass.finding.service.CommentsService;
import com.grass.finding.utils.ResultUtil;
import com.grass.finding.utils.WXUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/comment")
@Slf4j
public class CommentsController {

    @Autowired
    CommentsService commentsService;

    /**
     * 查询评论
     * @param lostId
     * @param request
     * @return
     */

    @GetMapping("/comments")
    public BaseResponse<List<List<Comments>>> getComments(Integer lostId,HttpServletRequest request){
//        String openId = WXUtil.getOpenId(request);
        List<List<Comments>> list = commentsService.getCommetsByLost(lostId);
        return ResultUtil.success(list);
    }

    /**
     * 保存评论
     * @param comments
     * @param request
     * @return
     */
    @PostMapping("/comments")
    public BaseResponse<Comments> postComments(@RequestBody Comments comments, HttpServletRequest request){
        String openId = WXUtil.getOpenId(request);
        comments.setOpenId(openId);
        if(comments.getLostId() == null || comments.getLostId() == 0){
            throw new BusinessException(ErrorCode.INVALID_PARAMETER, "请求的数据中应该包含lostId");
        }
        comments.setCreatTime(new Date(System.currentTimeMillis()));
        boolean save = commentsService.save(comments);
        if(!save){
            log.error("存储 comment 失败, comment为:", comments);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR);
        }
        return ResultUtil.success(comments);
    }

}
